from flask import Blueprint, request, jsonify
from app.Service.ClassificationService  import ClassificationService
from app.Utils.response import success, error
from app.Utils.exceptions import BusinessException
from app.db import db

classification_bp = Blueprint('classification', __name__, url_prefix='/myapp/admin/classification')
service = ClassificationService(db)


@classification_bp.route('/list', methods=['GET'])
def list_classifications():
    """分页查询分类"""
    page = request.args.get('page', default=1, type=int)
    page_size = request.args.get('pageSize', default=10, type=int)

    try:
        result = service.list_classifications(page, page_size)
        return jsonify(success(result, "分类分页查询成功"))
    except BusinessException as e:
        return jsonify(error(e.code, e.message))
    except Exception as e:
        return jsonify(error(500, f"服务器内部错误: {str(e)}"))


@classification_bp.route('/create', methods=['POST'])
def create_classification():
    """新增分类"""
    data = request.get_json()

    try:
        result = service.create_classification(data)
        return jsonify(success(result, "分类新增成功"))
    except BusinessException as e:
        return jsonify(error(e.code, e.message))
    except Exception as e:
        return jsonify(error(500, f"服务器内部错误: {str(e)}"))


@classification_bp.route('/<id>', methods=['GET'])
def get_classification(id):
    """查询回显"""
    try:
        result = service.get_classification(id)
        return jsonify(success(result, "分类查询成功"))
    except BusinessException as e:
        return jsonify(error(e.code, e.message))
    except Exception as e:
        return jsonify(error(500, f"服务器内部错误: {str(e)}"))


@classification_bp.route('/update', methods=['POST'])
def update_classification():
    """修改分类"""
    data = request.get_json()
    id = data.get('id')

    if not id:
        return jsonify(error(400, "缺少必要参数: id"))

    try:
        result = service.update_classification(id, data)
        return jsonify(success(result, "分类修改成功"))
    except BusinessException as e:
        return jsonify(error(e.code, e.message))
    except Exception as e:
        return jsonify(error(500, f"服务器内部错误: {str(e)}"))


@classification_bp.route('/delete', methods=['POST'])
def delete_classifications():
    """删除分类"""
    data = request.get_json()
    ids = data.get('ids', [])

    try:
        service.delete_classifications(ids)
        return jsonify(success(None, "分类批量删除成功"))
    except BusinessException as e:
        return jsonify(error(e.code, e.message))
    except Exception as e:
        return jsonify(error(500, f"服务器内部错误: {str(e)}"))

@classification_bp.route('/delete/<id>', methods=['DELETE'])
def delete_classification(id):
    """删除分类"""
    try:
        service.delete_classification(id)
        return jsonify(success(None, "分类删除成功"))
    except BusinessException as e:
        return jsonify(error(e.code, e.message))
    except Exception as e:
        return jsonify(error())